package com.lucksoft.map.sdk.gaode.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lucksoft.core.response.ApiResult;
import com.lucksoft.core.constant.BaseOperateConstant;

/**
 * 高德地图路线规划服务类
 * 
 * @author Qwen
 * @date 2025/10/9
 * @version 1.0.0
 */
@Service
public class MapSdkGaodeService {
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 获取高德地图路线信息
     * 
     * @param origin 起点坐标(纬度,经度)
     * @param destination 终点坐标(纬度,经度)
     * @param routeType 路线类型(driving/walking/riding)
     * @param tactics 路线偏好
     * @param ak 高德地图API Key
     * @return ApiResult 路线信息
     */
    public ApiResult getRouteInfo(String origin, String destination, String routeType, String tactics, String ak) {
        try {
            // 坐标格式转换：从纬度,经度转换为经度,纬度
            String convertedOrigin = convertCoordinates(origin);
            String convertedDestination = convertCoordinates(destination);
            
            // 根据路线类型选择API接口
            String apiUrl = getApiUrl(routeType);
            
            // 构建请求URL
            StringBuilder urlBuilder = new StringBuilder(apiUrl);
            urlBuilder.append("?key=").append(ak);
            urlBuilder.append("&origin=").append(convertedOrigin);
            urlBuilder.append("&destination=").append(convertedDestination);
            
            // 添加路线偏好参数
            if ("driving".equals(routeType)) {
                urlBuilder.append("&strategy=").append(tactics);
                // 显示预计耗时、道路收费、红绿灯等字段
                urlBuilder.append("&show_fields=").append("cost,tmcs,navi,cities,polyline,elocation,distance,duration,restriction,traffic_lights");
            }
            
            String url = urlBuilder.toString();
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            HttpEntity<String> entity = new HttpEntity<>(headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            
            if (response.getStatusCode().is2xxSuccessful()) {
                // 解析响应
                Map<String, Object> responseData = objectMapper.readValue(response.getBody(), new TypeReference<Map<String, Object>>() {});
                
                // 检查API响应状态
                String status = (String) responseData.get("status");
                if ("1".equals(status)) {
                    return new ApiResult(BaseOperateConstant.SUCCESS_CODE, BaseOperateConstant.SUCCESS_MSG, responseData);
                } else {
                    String info = (String) responseData.get("info");
                    return new ApiResult(BaseOperateConstant.FAILURE_CODE, "高德地图API错误: " + info, null);
                }
            } else {
                return new ApiResult(BaseOperateConstant.FAILURE_CODE, "HTTP请求失败，状态码: " + response.getStatusCode(), null);
            }
            
        } catch (Exception e) {
            return new ApiResult(BaseOperateConstant.FAILURE_CODE, "获取路线信息失败: " + e.getMessage(), null);
        }
    }
    
    /**
     * 根据路线类型获取API URL
     * 
     * @param routeType 路线类型
     * @return API URL
     */
    private String getApiUrl(String routeType) {
        switch (routeType) {
            case "driving":
                return "https://restapi.amap.com/v5/direction/driving";
            case "walking":
                return "https://restapi.amap.com/v5/direction/walking";
            case "riding":
                return "https://restapi.amap.com/v5/direction/bicycling";
            default:
                return "https://restapi.amap.com/v5/direction/driving";
        }
    }
    
    /**
     * 坐标格式转换：从纬度,经度转换为经度,纬度
     * 
     * @param coordinates 原始坐标(纬度,经度)
     * @return 转换后的坐标(经度,纬度)
     */
    private String convertCoordinates(String coordinates) {
        if (coordinates == null || coordinates.trim().isEmpty()) {
            return coordinates;
        }
        
        String[] parts = coordinates.split(",");
        if (parts.length == 2) {
            // 交换纬度和经度的位置
            return parts[1].trim() + "," + parts[0].trim();
        }
        
        return coordinates;
    }
}